package com.chaihu.front.service.validate.impl;

import com.alibaba.fastjson.JSONObject;
import com.chaihu.core.base.service.front.BaseComponentService;
import com.chaihu.core.cache.CommonCache;
import com.chaihu.core.cache.MappingCache;
import com.chaihu.core.context.IPageData;
import com.chaihu.core.factory.ValidateCodeFactory;
import com.chaihu.front.service.validate.ValidateCodeService;
import com.chaihu.utils.constant.MappingConstant;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 登录信息实现类
 * Created by wuxw on 2019/3/20.
 */

@Slf4j
@Service("validateCodeServiceImpl")
public class ValidateCodeServiceImpl extends BaseComponentService implements ValidateCodeService {

    @Autowired
    private RestTemplate restTemplate;


    /**
     * 生成验证码
     * 参考地址：https://www.cnblogs.com/happyfans/p/4486010.html
     *
     * @param pd 页面请求对象
     * @return
     */
    @Override
    public ResponseEntity<String> generateValidateCode(IPageData pd) {
        int w = 200, h = 80;
        String verifyCode = ValidateCodeFactory.generateVerifyCode(4);
        ResponseEntity<String> verifyCodeImage = null;
        try {
            verifyCodeImage = new ResponseEntity<>(ValidateCodeFactory.outputImage(200, 80, verifyCode), HttpStatus.OK);

            //将验证码存入Redis中
            log.info("请求 request id generate code : {}", pd.getRequestId() + "_validateCode");
            CommonCache.setValue(pd.getRequestId() + "_validateCode", verifyCode.toLowerCase(), CommonCache.defaultExpireTime);

        } catch (Exception e) {
            log.error("生成验证码失败，", e);
            verifyCodeImage = new ResponseEntity<>("", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return verifyCodeImage;
    }

    /**
     * 校验验证码
     *
     * @param pd 页面请求对象
     * @return
     */
    public ResponseEntity<String> validate(IPageData pd) {

        log.debug("校验验证码参数:{}", pd.toString());
        ResponseEntity<String> verifyResult = null;
        Assert.jsonObjectHaveKey(pd.getReqData(), "validateCode", "请求报文中未包含 validateCode节点" + pd.toString());

        // 万能图形验证码
        if (MappingConstant.VALUE_ON.equals(MappingCache.getValue(MappingConstant.KEY_UNIVERSAL_CAPTCHA_VALIDATION_CODE_ON_OFF)) && StringUtils.equals(MappingCache.getValue(MappingConstant.KEY_UNIVERSAL_CAPTCHA_VALIDATION_CODE), JSONObject.parseObject(pd.getReqData()).getString("validateCode"))) {
            // 跳过图形验证码校验
            return new ResponseEntity<>("跳过图形验证码", HttpStatus.OK);
        }

        String code = CommonCache.getValue(pd.getRequestId() + "_validateCode");
        log.info("请求 request id validate code:{}", pd.getRequestId() + "_validateCode");

        if (JSONObject.parseObject(pd.getReqData()).getString("validateCode").toLowerCase().equals(code)) {
            verifyResult = new ResponseEntity<>("成功", HttpStatus.OK);
        } else {
            pd.setToken("");
            verifyResult = new ResponseEntity<>("验证码错误或已失效", HttpStatus.INTERNAL_SERVER_ERROR);
        }


        return verifyResult;
    }

}
